package tech.jabari.user.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;
import tech.jabari.user.dao.UserDao;
import tech.jabari.user.entity.User;
import tech.jabari.user.mapper.UserMapper;
import tech.jabari.user.service.UserService;
import tech.jabari.utils.PageBean;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author Jabari Lu
 * @title: UserServiceImpl
 * @data 2020/8/27 14:23 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;


    @Autowired
    private UserMapper userMapper;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(User record) {
        return userMapper.insert(record);
    }

    @Override
    public int insertSelective(User record) {
        return userMapper.insertSelective(record);
    }

    @Override
    public User selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(User record) {
        return userMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(User record) {
        return userMapper.updateByPrimaryKey(record);
    }


    @Override
    public PageBean<User> selectAllUser(Map<String,Object> paramsMap) {
        // 获取分页参数，进行相应的逻辑处理
        Integer pageSize = (Integer) paramsMap.get("pageSize");
        Integer pageNo = (Integer) paramsMap.get("pageNo");
        Integer beginNo = (pageNo - 1) * pageSize;
        paramsMap.put("beginNo", beginNo);
       /* String username = (String)paramsMap.get("username");*/
        // 查询用户列表信息。
        List<User> userList = userDao.findAllUser(paramsMap);
        // 查询用户的总记录数。
        Integer totalRecords = userDao.findAllUserCount(paramsMap);
        // 计算总页数
        Integer pageNos = totalRecords / pageSize;
        if(totalRecords % pageSize!=0){
            pageNos = pageNos + 1;
       }
        PageBean pageBean = new PageBean(pageNo,pageSize);
        pageBean.setTotalRecords(totalRecords);
        pageBean.setTotalPageNum(pageNos);
        pageBean.setItems(userList);
        /**
         * "pageNos":3,
         * "totalRecords": 15,
         * "pageSize":5
         */

      return pageBean;
    }

    @Transactional
    @Override
    public Integer delUser(Integer id) {
        // 调用DAO删除用户
        Integer res = userDao.deleteUser(id);
        System.out.println("-------删除id为：" + id + "的用户成功！");
        // 模拟异常
//        int x = 1 / 0;
        return res;
    }



    @Override
    public int batchDelUser(String delIds) {
        Integer res = userDao.batchDeleteUser(delIds);
        return res;
    }


    @Override
    public User findUserById(Integer id) {
        User user = userDao.findById(id);
        return user;
    }

    @Override
    public List<User> getUserByUsernameAndPwd(String username, String pwd) {
        List<User> ret = userDao.selectUserByUsernameAndPwd(username, pwd);
        return ret;
    }


    @Override
    public List<User> getUserListByUsername(String username) {
        return userDao.selectUserByUsername(username);
    }


    @Override
    public Integer saveUser(User user, MultipartFile headImg, HttpServletRequest request) {
        // 处理图片上传。
        try {
            handleFileUpload(user, headImg, request);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 保存User信息到DB。
        return userDao.insertUser(user);
    }


    @Override
    public Integer updateUser(User user, MultipartFile headImg, HttpServletRequest request) {
        // 处理图片上传。
        try {
            handleFileUpload(user, headImg, request);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 更新User信息到DB。
        return userDao.updateUser(user);
    }

    /**
     * 处理图片上传
     * @param user
     * @param headImg
     * @param request
     * @throws IOException
     */
    private void handleFileUpload(@RequestBody User user,
                                  MultipartFile headImg,
                                  HttpServletRequest request) throws IOException {
        if (headImg != null && headImg.getSize() > 0) {
            // 保存图片
            String fileName = headImg.getOriginalFilename(); // 如：hello.jpg
            // 将图片名换成随机数格式。
            String fileNameSuffix = null;// 文件名的后辍
            int dotIndex = fileName.indexOf(".");
            if (dotIndex > -1) {
                fileNameSuffix = fileName.substring(dotIndex);  //如： .jpg
            }
            String randomUUID = UUID.randomUUID().toString();
            fileName = randomUUID + fileNameSuffix;

            String root = request.getServletContext().getRealPath("/upload");
            File rootDir = new File(root);
            if (!rootDir.exists()) {
                rootDir.mkdirs();
            }
            String headImgPath = root + File.separator + fileName;
            headImg.transferTo(new File(headImgPath));
            System.out.println("----------图片保存到服务器成功，路径：" + headImgPath);
            user.setHeadImg(fileName);
        }
    }


}
